% convert continuous EEGLAB  
% files to epoch data files
% -------------------------
subjectNames = { 'c1'  'c2'  'c3'  'c4'  'c5'  'c6'  'c7'  'c8' ...
                 'nd1' 'nd2' 'nd3' 'nd4' 'nd5' 'nd6' 'nd7' 'nd8' };
highpassFilter = 0.5;
lowpassFilter  = 50;

for index = 1:length(subjectNames)
    filenameset = fullfile(subjectNames{index}, [ subjectNames{index} '_continuous.set' ]); 
    EEG = pop_loadset(filenameset);

    % filtrage a 0.2
    disp('Filtering data...');
    for cind = 1:EEG.nbchan
       EEG.data(cind,:) = detrend(EEG.data(cind,:));
    end;
    EEG = pop_iirfilt( EEG, highpassFilter, 0, [], [0], 'on');
    EEG = pop_iirfilt( EEG,  0, lowpassFilter, [], [0], 'on');

    % extract all events
    % ------------------
    EEG = pop_epoch( EEG, {  'audio'  'blank'  'both'  'light'  }, [-3  3], 'newname', [ EEG.setname ' epochs' ], 'epochinfo', 'yes');
    %EEG = pop_rmbase( EEG, [-200  200]);
    EEG = pop_autorej(EEG, 'nogui', 'on', 'startprob', 5);
    
    filenameset = fullfile(subjectNames{index}, [ subjectNames{index} '_preprocessed.set' ]);
    EEG.group     = fastif(subjectNames{index}(1) == 'c', 'control', 'nondual');
    EEG.subject   = subjectNames{index};
    EEG = pop_saveset(EEG, filenameset);
end;
